package DemoText;
/**
 * 库存管理3 前 k 个最小的元素
 */

import java.util.Random;

public class LeetCodeLCR159 {
    public int[] inventoryManagement(int[] stock, int cnt) {
        int[] nums = new int[cnt];
        partition(stock, 0, stock.length - 1, cnt);
        for (int i = 0; i < cnt; i++) nums[i] = stock[i];
        return nums;
    }
    public void partition (int[] nums, int l, int r, int k) {
        if (l >= r) return;
        int key = nums[new Random().nextInt(r - l + 1) + l];
        int left = l - 1, right = r + 1, i = l;
        while (i < right) {
            if (nums[i] < key) swap(nums, ++left, i++);
            else if (nums[i] == key) i++;
            else swap(nums, --right, i);
        }
        //[l, left][left + 1, right - 1][right, r]
        int a = left - 1 + 1, b = right - left - 1;
        if (k <= a) partition(nums, l , left, k);
        else if (k <= a + b) return;
        else partition(nums, right, r, k);
    }
    public void swap (int[] nums, int i, int j) {
        int t = nums[i];
        nums[i] = nums[j];
        nums[j] = t;
    }
}
